<template>
  <div class="main-content" :class="{ hasTagsView: needTagsView }">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <a-card hoverable>
          <a-flex gap="small" justify="space-between">
            <a-form ref="queryFormRef" layout="inline" :model="queryParams">
              <a-form-item class="segmented-style">
                <el-segmented v-model="tableStyle" :options="tableOptions">
                  <template #default="scope">
                    <svg-icon :icon-class="scope.item['icon']" />
                  </template>
                </el-segmented>
              </a-form-item>
              <a-form-item name="mode">
                <a-select v-model:value="queryParams.mode" @change="handleQuery"
                          :options="exam_project_mode" :field-names="{label: 'label', value: 'value'}" />
              </a-form-item>
              <a-form-item name="status">
                <a-select v-model:value="queryParams.status" @change="handleQuery"
                          :options="exam_project_status" :field-names="{label: 'label', value: 'value'}" />
              </a-form-item>
              <a-form-item name="name">
                <a-input v-model:value="queryParams.name" placeholder="请输入项目名称" allow-clear
                         @keyup.enter="handleQuery" @blur="handleQuery" />
              </a-form-item>
              <a-flex justify="end">
                <el-button icon="Search" :loading="loading" round plain type="primary"
                           @click="handleQuery">搜索
                </el-button>
                <el-button icon="RefreshRight" :loading="loading" round
                           @click="resetQuery">重置
                </el-button>
              </a-flex>
            </a-form>
            <a-dropdown :trigger="['click']">
              <el-button type="primary" plain round icon="Plus" @click.prevent
                         v-hasPermi="['exam:project:add']" :loading="buttonLoading">
                新增
              </el-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="add" @click="handleAdd(ProjectMode.Exam)">
                    考试测评
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-flex>
        </a-card>
      </div>
    </transition>
    <a-spin :spinning="loading" size="large">
      <a-card ref="cardRef" hoverable class="card-content">
        <el-row :gutter="20" v-show="tableStyle==='Grid'" :style="{height:tableHeight+14+'px', overflowY: 'auto'}">
          <el-col :span="6" v-for="item in projectList" class="mb-5">
            <a-card hoverable>
              <a-flex justify="justify-between">
                <el-text tag="b" size="large" class="w-80%" truncated>{{ item.name }}</el-text>
                <dict-tag :options="exam_project_mode" :value="item.mode" />
              </a-flex>
              <div class="mt-2">
                <el-text v-if="item.status==='0'" size="small" type="warning" :underline="false">
                  <a-badge status="warning" />
                  未发布
                </el-text>
                <el-text v-if="item.status==='1'" size="small" type="success" :underline="false">
                  <a-badge status="processing" />
                  收集中
                </el-text>
              </div>
              <div class="mt-2">
                <el-text type="info"> {{ item.count || 0 }} 份数据</el-text>
                -
                                <el-text>总分 {{ item['survey']['attribute']['examScore'] }}</el-text>
              </div>
              <template #actions>
                <a-flex justify="end" gap="small" class="mr-3">
                  <el-tooltip placement="top">
                    <template #content>
                      <span>修改</span>
                    </template>
                    <el-button circle plain type="primary" icon="Edit"
                               @click="handleUpdate(item)"
                               v-hasPermi="['exam:project:edit']"></el-button>
                  </el-tooltip>
                  <el-tooltip placement="top">
                    <template #content>
                      <span>设置</span>
                    </template>
                    <el-button circle plain type="warning" icon="Setting"
                               @click="handleSetting(item)"
                               v-hasPermi="['exam:project:edit']"></el-button>
                  </el-tooltip>
                  <el-tooltip placement="top">
                    <template #content>
                      <span>项目数据</span>
                    </template>
                    <el-button circle plain type="warning"
                               @click="handleData(item)"
                               v-hasPermi="['exam:project:edit']">
                      <template #icon>
                        <svg-icon icon-class="data" />
                      </template>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip placement="top">
                    <template #content>
                      <span>统计报表</span>
                    </template>
                    <el-button circle plain
                               @click="handleReport(item)"
                               v-hasPermi="['exam:project:edit']">
                      <template #icon>
                        <svg-icon icon-class="statistics" />
                      </template>
                    </el-button>
                  </el-tooltip>
                  <a-dropdown>
                    <el-button circle icon="MoreFilled" />
                    <template #overlay>
                      <a-menu>
                        <a-menu-item
                          key="preview" @click="handlePreview(item)">
                          <svg-icon icon-class="preview" />
                          预览
                        </a-menu-item>
                        <a-menu-item
                          key="rename" @click="handleRename(item)">
                          <svg-icon icon-class="edit" />
                          重命名
                        </a-menu-item>
                        <a-menu-item
                          v-if="item.status==='0'"
                          key="release" @click="handleRelease(item)">
                          <svg-icon icon-class="publish" />
                          发布
                        </a-menu-item>
                        <a-menu-item
                          v-if="item.status==='1'"
                          key="cancelRelease" @click="handleCancelRelease(item)">
                          <svg-icon icon-class="unpublish" />
                          停止
                        </a-menu-item>
                        <a-menu-item
                          key="delete" @click="handleDelete(item)">
                          <svg-icon icon-class="delete" />
                          删除
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </a-flex>
              </template>
            </a-card>
          </el-col>
        </el-row>
        <a-empty style="margin-top:10% " v-if="projectList.length===0 &&tableStyle==='Grid'" />
        <template #title>
          <el-row ref="headerRef" :gutter="10" >
            <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" round
                         :disabled="selection.selectedKeys.value.length !== 1" @click="handleUpdate()"
                         v-hasPermi="['exam:project:edit']">修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" round
                         :disabled="selection.selectedKeys.value.length === 0" @click="handleDelete()"
                         v-hasPermi="['exam:project:remove']">删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain round icon="Download" @click="handleExport"
                         v-hasPermi="['exam:project:export']">
                导出
              </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @resetQuery="resetQuery" @queryTable="getList"
                           :columns="columns" />
          </el-row>
        </template>
        <el-auto-resizer v-show="tableStyle==='List'">
          <template #default="{height, width}">
            <el-table-v2 :columns="columns" :data="projectList" row-key="id"
                         :height="tableHeight+14" :width="width" fixed>
              <template #header-cell="{ column }">
                <template v-if="column.dataKey === 'selection'">
                  <el-checkbox
                    :model-value="selection.isAllSelected.value"
                    :indeterminate="selection.isIndeterminate.value"
                    @change="selection.toggleAll"
                  />
                </template>
              </template>
              <template #cell="{column,rowData,rowIndex}">
                <template v-if="column.dataKey==='selection'">
                  <el-checkbox
                    :model-value="selection.selectedKeys.value.some(k=>k=== rowData.id)"
                    @change="selection.toggleSelection(rowData.id)"
                  />
                </template>
                <template v-if="column.dataKey === 'index'">
                  {{ rowIndex + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
                </template>
                <template v-if="column.dataKey === 'mode'">
                  <dict-tag :options="exam_project_mode" :value="rowData.mode" />
                </template>
                <template v-if="column.dataKey === 'status'">
                  <dict-tag :options="exam_project_status" :value="rowData.status" />
                </template>
                <template v-if="column.dataKey === 'action'">
                  <el-tooltip placement="top">
                    <template #content>
                      <span>修改</span>
                    </template>
                    <el-button circle plain type="primary" icon="Edit"
                               @click="handleUpdate(rowData)"
                               v-hasPermi="['exam:project:edit']"></el-button>
                  </el-tooltip>
                  <el-tooltip placement="top">
                    <template #content>
                      <span>设置</span>
                    </template>
                    <el-button circle plain type="warning" icon="Setting"
                               @click="handleSetting(rowData)"
                               v-hasPermi="['exam:project:edit']"></el-button>
                  </el-tooltip>
                  <el-tooltip placement="top">
                    <template #content>
                      <span>项目数据</span>
                    </template>
                    <el-button circle plain type="warning"
                               @click="handleData(rowData)"
                               v-hasPermi="['exam:project:edit']">
                      <template #icon>
                        <svg-icon icon-class="data" />
                      </template>
                    </el-button>
                  </el-tooltip>
                  <a-dropdown>
                    <el-button circle icon="MoreFilled" />
                    <template #overlay>
                      <a-menu>
                        <a-menu-item
                          key="preview" @click="handlePreview(rowData)">
                          <svg-icon icon-class="preview" />
                          预览
                        </a-menu-item>
                        <a-menu-item
                          key="rename" @click="handleRename(rowData)">
                          <svg-icon icon-class="edit" />
                          重命名
                        </a-menu-item>
                        <a-menu-item
                          v-if="rowData.status==='0'"
                          key="release" @click="handleRelease(rowData)">
                          <svg-icon icon-class="publish" />
                          发布
                        </a-menu-item>
                        <a-menu-item
                          v-if="rowData.status==='1'"
                          key="cancelRelease" @click="handleCancelRelease(rowData)">
                          <svg-icon icon-class="unpublish" />
                          停止
                        </a-menu-item>
                        <a-menu-item
                          key="delete" @click="handleDelete(rowData)">
                          <svg-icon icon-class="delete" />
                          删除
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </template>
              </template>
            </el-table-v2>
          </template>
        </el-auto-resizer>
      </a-card>
    </a-spin>
    <a-card hoverable ref="paginationRef" v-show="total>0">
      <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList" />
    </a-card>
    <!-- 添加或修改项目对话框 -->
    <el-drawer :title="drawer.title" v-model="drawer.visible" :append-to-body="true" :show-close="false"
               :with-header="false" class="full-drawer"
               size="100%">
      <project-info :project-form="currentProject" :view-flag="viewFlag" @back="cancel" />
    </el-drawer>
    <el-dialog v-model="dialog.visible" width="400px">
      <template #header>
        <el-text tag="b">{{ dialog.title }}</el-text>
      </template>
      <el-form-item label="项目名称" prop="name">
        <a-input v-model:value="renameForm.name" />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitRename">确 定</el-button>
          <el-button @click="cancelDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Project" lang="ts">
import {
  addProject,
  cancelPublishProject,
  delProject,
  getProject,
  pageProject,
  publishProject, renameProject
} from '@/api/exam/project';
import {
  ProjectForm, ProjectMode,
  ProjectQuery,
  ProjectQuestionForm,
  ProjectVO
} from '@/api/exam/project/types';
import useSettingsStore from '@/store/modules/settings';
import ProjectInfo from './info/index.vue';
import { columns } from './data';

/*计算表格高度*/
import { useElTableHeight } from '@/utils/useElTableHeight';
import { ADD_PROJECT } from '@/views/exam/project/info/config';
import { tableOptions } from '@/types/type';
import router from '@/router';
import { getAntTagColor } from '@/utils/tagColor';
import { useSelection } from '@/utils/useSelection';

const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const paginationRef = ref<any>(null);
const { tableHeight } = useElTableHeight(cardRef, [headerRef, paginationRef]);
/*表格样式*/
const tableStyle = ref('Grid');
const settingsStore = useSettingsStore();
const needTagsView = computed(() => settingsStore.tagsView);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  exam_project_mode,
  exam_project_status
} = toRefs<any>(proxy?.useDict('exam_project_mode', 'exam_project_status'));

const projectList = ref<ProjectVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const projectFormRef = ref<ElFormInstance>();


const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});

const initFormData: ProjectForm = {
  id: undefined,
  name: undefined,
  survey: {
    children: []
  },
  mode: undefined,
  status: undefined,
  setting: undefined,
  remark: undefined
};
const data = reactive<PageData<ProjectForm, ProjectQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    name: undefined,
    mode: '',
    survey: undefined,
    status: '',
    setting: undefined,
    params: {}
  },
  rules: {
    id: [
      { required: true, message: '项目ID不能为空', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '项目名称不能为空', trigger: 'blur' }
    ],
    mode: [
      { required: true, message: '项目模式不能为空', trigger: 'change' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询项目列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageProject(queryParams.value);
  projectList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

// 使用多选逻辑
const selection = useSelection(
  projectList, 'id' // 指定唯一键字段
);

/** 表单重置 */
const reset = () => {
  currentProject.value = { ...initFormData };
  viewFlag.value = 'Edit';
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/*预览按钮操作*/

/*项目重命名*/
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const renameForm = ref({
  id: null,
  name: null
});
const cancelDialog = () => {
  resetRename();
  dialog.visible = false;
};
const resetRename = () => {
  renameForm.value = {
    id: null,
    name: null
  };
};
const handlePreview = (row: ProjectVO) => {
  const route = router.resolve({
    path: `/s/${row.id}`
  });
  window.open(route.href, '_blank');
};
const handleRename = async (row: ProjectVO) => {
  resetRename();
  renameForm.value.id = row.id;
  renameForm.value.name = row.name;
  dialog.title = '项目重命名';
  dialog.visible = true;
};
const submitRename = async () => {
  if (renameForm.value.name) {
    buttonLoading.value = true;
    await renameProject(renameForm.value).finally(() => buttonLoading.value = false);
    proxy?.$modal.notifySuccess('重命名成功');
    dialog.visible = false;
    await getList(); // 刷新列表
  } else {
    proxy?.$modal.notifyError('项目名称不能为空');
  }
};
/*发布按钮操作*/
const handleRelease = async (row?: ProjectVO) => {
  await proxy?.$modal.modal('确定发布当前项目? ', '只有发布的项目才能收集数据', 'success');
  await publishProject(row.id);
  proxy?.$modal.notifySuccess('已发布');
  await getList();
};
/*停止按钮操作*/
const handleCancelRelease = async (row: ProjectVO) => {
  await proxy?.$modal.modal('确定停止当前项目？', '停止之后项目将不能继续收集数据');
  await cancelPublishProject(row.id);
  proxy?.$modal.notifySuccess('已停止');
  await getList();
};

/** 新增按钮操作 */
const currentProject = ref<ProjectForm>();
const viewFlag = ref();
const handleAdd = async (mode: string) => {
  buttonLoading.value = true;
  reset();
  form.value = ADD_PROJECT[mode];
  const res = await addProject(form.value).finally(() => buttonLoading.value = false);
  currentProject.value = res.data;
  viewFlag.value = 'Edit';
  drawer.visible = true;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProjectVO) => {
  const _projectId = row?.id || selection.selectedKeys.value[0];
  const res = await getProject(_projectId);
  currentProject.value = res.data;
  viewFlag.value = 'Edit';
  drawer.visible = true;
};
/** 设置按钮操作 */
const handleSetting = async (row?: ProjectVO) => {
  const _projectId = row?.id || selection.selectedKeys.value[0];
  const res = await getProject(_projectId);
  currentProject.value = res.data;
  viewFlag.value = 'Setting';
  drawer.visible = true;
};
//
const handleData = async (row?: ProjectVO) => {
  const _projectId = row?.id || selection.selectedKeys.value[0];
  const res = await getProject(_projectId);
  currentProject.value = res.data;
  viewFlag.value = 'Data';
  drawer.visible = true;
};
const handleReport=async (row?: ProjectVO) => {
  const _projectId = row?.id || selection.selectedKeys.value[0];
  const res = await getProject(_projectId);
  currentProject.value = res.data;
  viewFlag.value = 'Report';
  drawer.visible = true;
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProjectVO) => {
  const _projectIds = row?.id || selection.selectedKeys.value;
  let length = row ? 1 : selection.selectedKeys.value.length;
  await proxy?.$modal.modal('删除数据', '确认删除这 ' + `<font color="red"> ${length}</font>` + ' 条数据吗？');
  await delProject(_projectIds);
  proxy?.$modal.notifySuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('exam/project/export', {
    ...queryParams.value
  }, `project_${new Date().getTime()}.xlsx`);
};


/** 关闭按钮 */
const cancel = () => {
  // 重置
  reset();
  drawer.visible = false;
  getList();
};


onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>

</style>

